import React, { useEffect, useContext, useState } from 'react';
import { Form, Button, Modal, Space, Row, Col, message } from 'antd';
import { useForm } from 'antd/lib/form/Form';
import { InspectorContext } from '../FlowManage';
import { MinusCircleOutlined, PlusOutlined, EditOutlined, DeleteOutlined } from '@ant-design/icons';
import { CustomFormItemsHoc } from './CustomFormHoc';
import { cloneDeep } from 'lodash';

/**
 * 条件组件
 * 示例： AI管理-机器人管理-版本管理-配置话术流程-条件组件
 */
const ConditionComponent: React.FC = () => {
  const [form] = useForm();
  const [formAdd] = Form.useForm();
  const { selectedData, onInputChange, onRemoveLink, onModifyLink, isView } =
    useContext(InspectorContext);
  const { Input, Select, Option } = CustomFormItemsHoc({ disabled: isView });
  const children: any = [];
  const pressArrayOrigin = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, '*', '#'];

  pressArrayOrigin.forEach(item => {
    // @ts-ignore：忽略检测, 应该是GoJS TS声明有问题
    children.push(<Option key={item}>{item}</Option>);
  });

  // 变量操作类型 0-新增 1-编辑
  const [actionType, setActionType] = useState<0 | 1>(0);
  // 添加条件：弹框显示
  const [visible, setVisible] = useState(false);
  // 添加条件：确认按钮loading
  const [confirmLoading, setConfirmLoading] = useState(false);

  // 编辑条件：index
  const [modifyIdx, setModifyIdx] = useState<number>(-1);

  useEffect(() => {
    // 需要手动设置form数据, initialValue初始化属性在切换同组件的props数据时不会更新
    form.setFieldsValue(selectedData);
    form.validateFields();
  }, [form, selectedData]);

  /**
   * 添加条件点击取消或者右上角关闭
   */
  const handleCancel = () => {
    console.log('Clicked cancel button');
    formAdd.resetFields();
    setVisible(false);
  };

  /**
   * 添加条件表单提交
   * @param values
   */
  const onFinish = (values: any) => {
    console.log('onFinish', values);
    // value内的describe去除前后空格
    values.describe = values.describe.trim();
    values.status = 0;

    // setConfirmLoading(true);

    const conditionArray = cloneDeep(selectedData.conditionArray);
    if (actionType === 0) {
      // 新增
      const describeArray = selectedData.conditionArray.map((item: any) => {
        return item.describe;
      });

      // 判断条件名是否与之前的重复
      if (describeArray.includes(values.describe)) {
        message.error('条件名已存在');
        return;
      }

      conditionArray.push(values);
    } else {
      // 编辑
      const describeArray = selectedData.conditionArray
        .filter((item: any, index: number) => {
          return index !== modifyIdx;
        })
        .map((item: any) => {
          return item.describe;
        });

      // 判断条件名是否与之前的重复
      if (describeArray.includes(values.describe)) {
        message.error('条件名已存在');
        return;
      }
      const beforeModifyDescribe = conditionArray[modifyIdx].describe;

      onModifyLink('fromPort', beforeModifyDescribe, values.describe, selectedData.key);
      conditionArray[modifyIdx] = values;
    }

    onInputChange('conditionArray', conditionArray, true);

    setVisible(false);
    // setConfirmLoading(false);
    formAdd.resetFields();
  };

  /**
   * 编辑操作
   * @param idx 所编辑数据的index
   */
  const modifyAction = (idx: number) => {
    console.log('编辑', idx);
    const { describe, expressions } = selectedData.conditionArray[idx];

    setActionType(1);
    setModifyIdx(idx);
    setVisible(true);
    formAdd.setFieldsValue({
      describe,
      expressions,
    });
  };

  /**
   * 删除操作
   * @param idx 所删除数据的index
   */
  const deleteAction = (idx: number) => {
    console.log('删除', idx);
    const conditionArray = cloneDeep(selectedData.conditionArray);
    const describe = conditionArray[idx].describe;

    conditionArray.splice(idx, 1);
    onInputChange('conditionArray', conditionArray, true);
    onRemoveLink('fromPort', describe, selectedData.key);

    setVisible(false);
    setConfirmLoading(false);
    formAdd.resetFields();
  };

  return (
    <>
      <Form layout="vertical" form={form}>
        <Form.Item
          label="条件组件名称"
          initialValue=""
          name="title"
          rules={[
            {
              required: true,
              whitespace: true,
              max: 10,
              message: '仅支持输入10个以内字符',
            },
          ]}
          getValueFromEvent={event => {
            return event.target.value.replace(/\s+/g, '');
          }}
        >
          <Input
            maxLength={10}
            onChange={(e: { target: { value: any }; type: string }) => {
              onInputChange('title', e.target.value, e.type === 'blur');
            }}
            onBlur={(e: { target: { value: any }; type: string }) => {
              onInputChange('title', e.target.value, e.type === 'blur');
            }}
          />
        </Form.Item>

        <Form.Item label="条件设置" required>
          <Button
            disabled={isView}
            type="primary"
            onClick={() => {
              setVisible(true);
              setActionType(0);
              formAdd.setFieldsValue({
                describe: '',
                expressions: [{ condition: '>' }],
              });
            }}
          >
            添加条件
          </Button>

          {selectedData.conditionArray.map((item: any, index: number) => {
            return (
              item && (
                <Row key={`${item.describe}${index}`} justify="space-between" align="middle">
                  <Col>{item.describe}</Col>
                  <Col>
                    <Button
                      disabled={isView}
                      type="link"
                      icon={<EditOutlined />}
                      onClick={() => {
                        modifyAction(index);
                      }}
                    />
                    <Button
                      disabled={isView}
                      type="link"
                      icon={<DeleteOutlined />}
                      onClick={() => {
                        deleteAction(index);
                      }}
                    />
                  </Col>
                </Row>
              )
            );
          })}
        </Form.Item>
      </Form>
      <Modal
        title={actionType === 0 ? `添加条件${selectedData.conditionArray.length + 1}` : '编辑条件'}
        visible={visible}
        onOk={() => {
          formAdd.submit();
        }}
        confirmLoading={confirmLoading}
        onCancel={handleCancel}
      >
        <Form
          form={formAdd}
          onFinish={onFinish}
          initialValues={{ describe: '', expressions: [{}] }}
        >
          <Form.Item
            name={['describe']}
            label="条件名"
            rules={[
              {
                required: true,
                message: '仅支持输入10个以内字符',
                whitespace: true,
                max: 10,
              },
            ]}
            getValueFromEvent={event => {
              return event.target.value.replace(/\s+/g, '');
            }}
          >
            <Input maxLength={10} placeholder="例如“户口不在深圳”" />
          </Form.Item>
          <Form.List name="expressions">
            {(fields, { add, remove }) => {
              return (
                <div style={{ maxHeight: 300, overflow: 'auto' }}>
                  {fields.map(field => (
                    <Space
                      key={field.key}
                      style={{
                        display: 'flex',
                        justifyContent: 'space-between',
                        marginBottom: 8,
                      }}
                      align="baseline"
                    >
                      <Form.Item
                        {...field}
                        name={[field.name, 'leftVal']}
                        fieldKey={[field.fieldKey, 'leftVal']}
                        rules={[
                          {
                            required: true,
                            whitespace: true,
                            message: '请输入变量',
                          },
                        ]}
                        getValueFromEvent={event => {
                          return event.target.value.replace(/\s+/g, '');
                        }}
                      >
                        <Input placeholder="变量名" />
                      </Form.Item>

                      <Form.Item
                        {...field}
                        name={[field.name, 'condition']}
                        fieldKey={[field.fieldKey, 'condition']}
                        rules={[
                          {
                            required: true,
                            whitespace: true,
                            message: '请选择',
                          },
                        ]}
                        initialValue=">"
                      >
                        <Select
                          placeholder="请选择"
                          style={{ width: 60 }}
                          getPopupContainer={(triggerNode: { parentElement: any }) =>
                            triggerNode.parentElement
                          }
                        >
                          <Option value=">">&gt;</Option>
                          <Option value="<">&lt;</Option>
                          <Option value="=">=</Option>
                          <Option value="≠">≠</Option>
                          <Option value="≥">≥</Option>
                          <Option value="≤">≤</Option>
                        </Select>
                      </Form.Item>

                      <Form.Item
                        {...field}
                        name={[field.name, 'rightVal']}
                        fieldKey={[field.fieldKey, 'rightVal']}
                        rules={[
                          {
                            required: true,
                            whitespace: true,
                            message: '请输入比较值',
                          },
                        ]}
                        getValueFromEvent={event => {
                          return event.target.value.replace(/\s+/g, '');
                        }}
                      >
                        <Input placeholder="比较值" />
                      </Form.Item>

                      {fields.length > 1 && (
                        <MinusCircleOutlined
                          onClick={() => {
                            remove(field.name);
                          }}
                        />
                      )}
                    </Space>
                  ))}

                  <Form.Item>
                    <Button
                      type="dashed"
                      onClick={() => {
                        add();
                      }}
                      block
                    >
                      <PlusOutlined /> 添加条件表达式
                    </Button>
                  </Form.Item>
                </div>
              );
            }}
          </Form.List>
        </Form>
      </Modal>
    </>
  );
};

export default ConditionComponent;
